﻿using Windows.ApplicationModel.Background;

namespace WinRT.SIP.UI.BackgroundTasks
{
    public static class BackgroundTaskHelper
    {
        /// <summary>
        /// Registers the background task.
        /// </summary>
        /// <param name="taskEntryPoint">The task entry point.</param>
        /// <param name="name">The task name.</param>
        /// <param name="trigger">The trigger.</param>
        /// <param name="condition">The condition.</param>
        /// <returns></returns>
        public static BackgroundTaskRegistration RegisterBackgroundTask(string taskEntryPoint, string name, IBackgroundTrigger trigger, IBackgroundCondition condition)
        {
            var builder = new BackgroundTaskBuilder();

            builder.Name = name;
            builder.TaskEntryPoint = taskEntryPoint;
            builder.SetTrigger(trigger);

            if (condition != null)
            {
                builder.AddCondition(condition);
            }

            return builder.Register();
        }

        /// <summary>
        /// Unregisters the background task.
        /// </summary>
        /// <param name="name">The task name.</param>
        public static void UnregisterBackgroundTask(string name)
        {
            foreach (var task in BackgroundTaskRegistration.AllTasks)
            {
                if (task.Value.Name == name)
                {
                    task.Value.Unregister(true);
                    return;
                }
            }
        }

        /// <summary>
        /// Determines whether [is task registered] [the specified name].
        /// </summary>
        /// <param name="name">The task name.</param>
        /// <returns>
        ///   <c>true</c> if [is task registered] [the specified name]; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsTaskRegistered(string name)
        {
            foreach (var task in BackgroundTaskRegistration.AllTasks)
            {
                if (task.Value.Name == name)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
